package com.tanhua.common.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.common.config.AliyunUploadPicConfig;
import com.tanhua.common.vo.UploadPicResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@Service
public class UploadPicService {
    private static final String[] IMAGE_TYPE = {".bmp", ".jpg", ".jpeg", ".gif", ".png"};
    @Autowired
    private OSSClient ossClient;
    @Autowired
    private AliyunUploadPicConfig aliyunUploadPicConfig;

    public UploadPicResult uploadPic(MultipartFile multipartFile) {
        UploadPicResult uploadPicResult = new UploadPicResult();
        boolean legal = false;
        String filename = multipartFile.getOriginalFilename();
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWith(filename, type)) {
                legal = true;
                break;
            }
        }
        if (!legal) {
            uploadPicResult.setStatus("error");
            return uploadPicResult;
        }

        String filePath = getFilePath(filename);
        // 上传到阿里云
        try {
            // 目录结构：images/2018/12/29/xxxx.jpg
            ossClient.putObject(aliyunUploadPicConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(multipartFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            uploadPicResult.setStatus("error");
            return uploadPicResult;
        }

        // 上传成功
        uploadPicResult.setStatus("done");
        uploadPicResult.setName(this.aliyunUploadPicConfig.getUrlPrefix() + filePath);
        uploadPicResult.setUid(String.valueOf(System.currentTimeMillis()));

        return uploadPicResult;
    }

    private String getFilePath(String filename) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(filename, ".");
    }
}
